package com.banzhi.shop.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.Guigeadapter;
import com.banzhi.shop.adapter.HomeFrgAda;
import com.banzhi.shop.adapter.SucaiAdapter;
import com.banzhi.shop.adapter.ViewPagerAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.ChoiceDetailsData;

import com.banzhi.shop.entity.GoodsDetails.Buy_Data;



import com.banzhi.shop.entity.GoodsDetails.GoodsSucai_Data;
import com.banzhi.shop.entity.GoodsDetails.Guige.Guige_Data;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.fragment.ChoiceGoodsIntroductionFrg;
import com.banzhi.shop.fragment.ChoiceGoodsParameterFrg;
import com.banzhi.shop.fragment.ChoicePurchaseNotesFrg;

import com.banzhi.shop.model.CallBack.CommodityDetailsCallBack;
import com.banzhi.shop.model.CallBack.CommoditySucaiCallBack;
import com.banzhi.shop.model.CallBack.GuigeCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;

import com.banzhi.shop.model.Impl.ChoiceDetailsImpl;
import com.banzhi.shop.model.Impl.ChoiceGuigeImpl;
import com.banzhi.shop.model.Impl.ChoiceSucaiImpl;


import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.qimo.View.PeerDialog;
import com.banzhi.shop.qimo.activity.ChatActivity;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.AndroidUtil;
import com.banzhi.shop.utils.DateUtil;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.TabLayoutUtil;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.banzhi.shop.utils.XutilImage;
import com.banzhi.shop.view.BadgeView;
import com.banzhi.shop.view.CustomSwipeToRefresh;
import com.banzhi.shop.view.DragFloatActionButton;
import com.moor.imkf.GetPeersListener;
import com.moor.imkf.IMChatManager;
import com.moor.imkf.InitListener;
import com.moor.imkf.model.entity.Peer;
import com.moor.imkf.utils.NetUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;

import static com.banzhi.shop.MyApp.accessID;
import static com.banzhi.shop.R.id.rl_fuzhi;
import static com.banzhi.shop.utils.ASUtils.setAlpha;

/**
 * 商品详情页界面
 */
public class ChoicesDetailsActivity extends BaseActivity implements View.OnClickListener, CommodityDetailsCallBack,
        CommoditySucaiCallBack, SwipeRefreshLayout.OnRefreshListener, Guigeadapter.GettextCallBack, WXshareCallBack, SucaiAdapter.ShareCallBack, GuigeCallBack {
    /**
     * 上面的轮播图
     */
    private ViewPager viewpager;
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 点击传过来的商品的ID
     */
    private String goodID;
    /**
     * 详情页面的按钮
     */
    private Button btn_xiangqing;
    /**
     * 素材页面的按钮
     */
    private Button btn_sucai;
    /**
     * 详情页面的布局
     */
    private LinearLayout ll_xiangqing;
    /**
     * 素材页面的布局
     */
    private RelativeLayout rlsucai;
    /**
     * 商详情里的导航栏
     */
    private TabLayout tabLayout;
    /**
     * 商品详情你的viewpager
     */
    private ViewPager vpgoodsdata;
    /**
     * 分享
     */
    private ImageView ivshare;
    /**
     * 商品标题
     */
    private TextView tvtitle;
    /**
     * 商品价格
     */
    private TextView tvprice;
    /**
     * 商品利润
     */
    private TextView tvlirun;
    /**
     * 商品库存
     */
    private TextView tvkucun;
    /**
     * 商品在售人数
     */
    private TextView tvpeoplenum;
    /**
     * 商品状态   控制是特卖开始前发生特卖开始中
     */
    private TextView tvstuta;
    /**
     * 特卖的小时
     */
    private TextView tvhour;
    /**
     * 特卖的分钟
     */
    private TextView tvminute;
    /**
     * 特卖的秒
     */
    private TextView tvsecond;
    /**
     * 选择规格
     */
    private RelativeLayout rlchoiceguige;
    /**
     * 特卖商品的布局
     */
    private LinearLayout lltemai;
    /**
     * 购物车的布局
     */
    private TextView llCart;
    /**
     * 商品详情数据实体类
     */
  //  private GoodsDetails_Data goodsdata;

    /**
     * 第几张图片
     */
    private TextView tvnum;
    /**
     * 图片的总张数
     */
    private TextView tvall;
    /**
     * 展示图片的imageview集合
     */
    private List<ImageView> titleimage = new ArrayList<>();
    /**
     * 图片的URI地址集合
     */
    private List<String> imageResIDs = new ArrayList<>();
    /**
     * 素材实体类集合
     */
    private List<GoodsSucai_Data> sucaidata = new ArrayList<>();
  //  private ICommodityDetailsModel model;
    //private ICommoditySucaiModel sucaiModel;
    private Timer timer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            showTemaiDate();
        }
    };

    /**
     * 默认商品数量为1
     */
    private int number = 1;
    /**
     * 素材页面的下拉刷新
     */
    private CustomSwipeToRefresh srllistview;
    /**
     * 素材列表页面
     */
    private ListView lvsucai;
    private SucaiAdapter adapter;

    /**
     * 商品规格的adapter
     */
    private Guigeadapter guigeadapter;

    /**
     * 存储用户点击选择的规格属性
     */
    private int[] strs;

    /**
     * 用来存储商品选择后的规格
     */
    private String guige;
    /**
     * 用来选择商品选择后数量
     */
    private String goodsnum;
    /**
     * 选择规格后的显示
     */
    private TextView tvchoice;

    /**
     * 买
     */
    private LinearLayout tvbuy;
    /**
     * 买
     */
    private TextView tvsell;

    /**
     * 点击选择规格你的确定时  来判断去做什么事情
     * 点击选择规格  type ==1；
     * 点击加入购物车  type ==2;
     * 点击买        type==3;
     */
    private int type = 1;
    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
//    /**
//     * 分页加载
//     */
//    private int sucaipage = 1;
//    /**
//     * 判断listview是不是滑到最低端了
//     */
//    private boolean isbottom;

    private TextView tvmaohao;
    private TextView tvmaohao2;
    private RelativeLayout rlnodata;
    private int width;
    private int height;

    private LinearLayout llkucun;

    private boolean iscanbuy = true;

    //private IGuigeModel guigeModel;
    private Guige_Data guigedata;
    private DragFloatActionButton actionButton;
    private LinearLayout llendprice;
    private TextView tvendprice;
    private BadgeView badgeView;

    private LinearLayout llxiangou;
    private TextView tvxiangou;
    private LinearLayout mLlll;
    private LinearLayout mLlCommdityProfit;
    private ChoiceDetailsImpl model;
    private ChoiceSucaiImpl sucaiModel;
    private ChoiceGuigeImpl guigeModel;
    private TextView mTvChoiceName;
  //  private CateBean mCateBean;
    private ChoiceDetailsData.GoodsBean goodsdata;

    private ChoiceDetailsData.CateBean mCateBean;
    private ChoiceDetailsData mGoodsDetailsData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice_details);
        Translucent.setTranslucent(this);
        ShareSDK.initSDK(this, "1dc05ab16fd6c");
        setinits();
        setListeners();

        Intent intent = getIntent();
        goodID = intent.getStringExtra("id");
        //type ==1 跳到详情页
        String type = intent.getStringExtra("type");
        if ("1".equals(type)) {
            btn_xiangqing.setBackgroundResource(R.mipmap.bg4);
            btn_sucai.setBackgroundResource(R.mipmap.bg5);
            ll_xiangqing.setVisibility(View.GONE);
            rlsucai.setVisibility(View.VISIBLE);
            btn_sucai.setTextColor(ContextCompat.getColor(this, R.color.themeColor));
            btn_xiangqing.setTextColor(Color.WHITE);
        }
        showFragment();
      //  model = new CommodityDetailsImpl();
        model = new ChoiceDetailsImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(goodID, "0", this);
    //    sucaiModel = new CommoditySucaiImpl();
        sucaiModel = new ChoiceSucaiImpl();
        wxmodel = new WXshareImpl();
     //  guigeModel = new GuigeImpl();
        guigeModel = new ChoiceGuigeImpl();

    }

    @Override
    protected void onStart() {
        super.onStart();
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                TabLayoutUtil.setIndicator(tabLayout, 35, 35);
            }
        });
    }
    /**
     * 显示品详情里面的fragent
     */
    private void showFragment() {
        List<Fragment> list_fragment = new ArrayList<>();
        list_fragment.add(new ChoiceGoodsIntroductionFrg());//商品介绍
        list_fragment.add(new ChoiceGoodsParameterFrg());//详情参数
        list_fragment.add(new ChoicePurchaseNotesFrg());//购买须知

        List<String> list_title = new ArrayList<>();
        list_title.add("商品介绍");
        list_title.add("详情参数");
        list_title.add("购买须知");

        HomeFrgAda hfadapter = new HomeFrgAda(getSupportFragmentManager(), list_fragment, list_title);
        vpgoodsdata.setAdapter(hfadapter);
        //将tabLayout与viewpager连起来
        tabLayout.setupWithViewPager(vpgoodsdata);
    }


    private void setinits() {
        actionButton = (DragFloatActionButton) findViewById(R.id.action_button);
        // 设置返回主页的按钮
        viewpager = (ViewPager) findViewById(R.id.vp_title);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        width = dm.widthPixels;
        height = width;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
        //获取当前控件的布局对象
        //params.height=width;//设置当前控件布局的高度
        viewpager.setLayoutParams(params);//将设置好的布局参数应用到控件中

        ivback = (ImageView) findViewById(R.id.iv_back);
        btn_xiangqing = (Button) findViewById(R.id.btn_xiangqing);
        btn_sucai = (Button) findViewById(R.id.btn_sucai);
        ll_xiangqing = (LinearLayout) findViewById(R.id.ll_xiangqing);
        rlsucai = (RelativeLayout) findViewById(R.id.rl_sucai);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        vpgoodsdata = (ViewPager) findViewById(R.id.vp_goods_data);
        vpgoodsdata.setOffscreenPageLimit(2);//同时加载旁边的fragment的页面布局

        ivshare = (ImageView) findViewById(R.id.iv_share);
        tvtitle = (TextView) findViewById(R.id.tv_title);
        tvprice = (TextView) findViewById(R.id.tv_price);
        tvlirun = (TextView) findViewById(R.id.tv_liyun);
        tvkucun = (TextView) findViewById(R.id.tv_kucun);
        tvpeoplenum = (TextView) findViewById(R.id.tv_Peoplenum);
        lltemai = (LinearLayout) findViewById(R.id.ll_temai);
        tvstuta = (TextView) findViewById(R.id.tv_statu);
        tvhour = (TextView) findViewById(R.id.tv_hour);
        tvminute = (TextView) findViewById(R.id.tv_minute);
        tvsecond = (TextView) findViewById(R.id.tv_second);
        srllistview = (CustomSwipeToRefresh) findViewById(R.id.srl_listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);

        lvsucai = (ListView) findViewById(R.id.sucai_listview);
        rlchoiceguige = (RelativeLayout) findViewById(R.id.rl_choice_guige);
        llCart = (TextView) findViewById(R.id.ll_gouwuche);
        tvchoice = (TextView) findViewById(R.id.tv_choice);
        tvbuy = (LinearLayout) findViewById(R.id.tv_buy);
        tvsell = (TextView) findViewById(R.id.tv_sell);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
        //图片的张数和第几张图片
        tvnum = (TextView) findViewById(R.id.tv_num);
        tvall = (TextView) findViewById(R.id.tv_all);

        tvmaohao = (TextView) findViewById(R.id.tv_maohao);
        tvmaohao2 = (TextView) findViewById(R.id.tv_maohao2);

        llkucun = (LinearLayout) findViewById(R.id.ll_kucun);
        llendprice = (LinearLayout) findViewById(R.id.ll_endprice);
        tvendprice = (TextView) findViewById(R.id.tv_endprice);
        badgeView = new BadgeView(this);
        llxiangou = (LinearLayout) findViewById(R.id.ll_xiangou);
        tvxiangou = (TextView) findViewById(R.id.tv_xiangou);
        mLlCommdityProfit = (LinearLayout) findViewById(R.id.ll_commodity_profit);
        mTvChoiceName = (TextView) findViewById(R.id.tv_choice_name);


    }

    /**
     * new  imageview  首页图片设置到imageview上
     */
    private void prepareData() {
        ImageView iv;
        for (int i = 0; i < imageResIDs.size(); i++) {
            iv = new ImageView(this);
            XutilImage.display(iv, imageResIDs.get(i));
            titleimage.add(iv);
        }

    }

    /**
     * 库存
     */
    private String num;
    private int Curr_position;
    private void setListeners() {
        tvtitle.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                fuzhiPopupwindow();
                return false;
            }
        });
        srllistview.setOnRefreshListener(this);
        ivback.setOnClickListener(this);
        btn_sucai.setOnClickListener(this);
        btn_xiangqing.setOnClickListener(this);
        ivshare.setOnClickListener(this);
        rlchoiceguige.setOnClickListener(this);
        llCart.setOnClickListener(this);
        tvbuy.setOnClickListener(this);
        tvsell.setOnClickListener(this);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvnum.setText(position + 1 + "");
                // Curr_position = position;

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断版本若为6.0申请权限
                if (Build.VERSION.SDK_INT < 23) {
                    init();
                } else {
                    //6.0
                    if (ContextCompat.checkSelfPermission(ChoicesDetailsActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                        //该权限已经有了
                        init();
                    } else {
                        //申请该权限
                        ActivityCompat.requestPermissions(ChoicesDetailsActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0x1111);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_xiangqing:
                btn_xiangqing.setBackgroundResource(R.mipmap.bg1);
                btn_sucai.setBackgroundResource(R.mipmap.bg2);
                ll_xiangqing.setVisibility(View.VISIBLE);
                rlsucai.setVisibility(View.GONE);
                btn_xiangqing.setTextColor(ContextCompat.getColor(this, R.color.themeColor));
                btn_sucai.setTextColor(Color.WHITE);
                break;
            case R.id.btn_sucai:
                btn_xiangqing.setBackgroundResource(R.mipmap.bg4);
                btn_sucai.setBackgroundResource(R.mipmap.bg5);
                ll_xiangqing.setVisibility(View.GONE);
                rlsucai.setVisibility(View.VISIBLE);
                btn_sucai.setTextColor(ContextCompat.getColor(this, R.color.themeColor));
                btn_xiangqing.setTextColor(Color.WHITE);
                break;
            case R.id.iv_share:
                if ("1".equals(MyApp.loginMessage.getString("isagent", ""))) {
                    showSharePopupwindow();

                }else {
                    showBeShoperPopupWindow();
                }
                break;
            case R.id.rl_choice_guige:
                //规格选择
                type = 1;
                if (guigedata == null) {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    guigeModel.getGuige(goodsdata.getId(), this);
                } else {
                    showGuige();
                }
                break;
            case R.id.ll_gouwuche:
                //购物车
         //       LogUtils.e("Tooken", MyApp.loginMessage.getString("token", ""));
                if ("".equals(MyApp.loginMessage.getString("token", ""))) {
                    showLoginPopupWindow();
                }else {

                    if (iscanbuy) {
                        type = 2;
                        if (guigedata == null) {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            guigeModel.getGuige(goodsdata.getId(), this);
                        } else {
                            showGuige();
                        }
                    } else {
                        ToastUtils.makeToastShort("特卖还没开始，请等待");
                    }
                }
                break;
            case R.id.tv_buy:
                if ("".equals(MyApp.loginMessage.getString("token", ""))) {
                    showLoginPopupWindow();
                }else {
                    //任選結算
                    startActivity( new Intent(ChoicesDetailsActivity.this,ChoiceShoppingCartActivity.class));

                }
                break;
            case R.id.tv_sell:
                if ("1".equals(MyApp.loginMessage.getString("isagent", ""))) {
                    showSharePopupwindow();

                }else {
                    showBeShoperPopupWindow();
                }
                break;
        }
    }
    private void showBeShoperPopupWindow() {
        View contentView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.popupwindow_shoper2, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                startActivity(new Intent(ChoicesDetailsActivity.this,BecomeShoperActivity.class));

                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.activity_grouping_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
    private void showWindow() {
        View contentView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.popumwindow_yu_e3, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应

        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void showLoginPopupWindow() {
        View contentView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.popupwindow_login, null);
        int width = LinearLayout.LayoutParams.MATCH_PARENT;
        int height = WindowManager.LayoutParams.MATCH_PARENT;
        final PopupWindow popupWindow = new PopupWindow(contentView, width, height);
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);//允许在外点击消失
        //设置各个控件 的点击相应
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvTrue = (TextView) contentView.findViewById(R.id.tv_true);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //   LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在上架,请稍后~");

                startActivity(new Intent(ChoicesDetailsActivity.this,NewLoginActivity.class));

                SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                editor.putString("token", "");
                editor.putString("personNickname", "");
                editor.putString("personAvatar", "");
                editor.putString("personBirth", "");
                editor.putString("personGender", "");
                editor.putString("shopname", "");
                editor.putString("shoplogo", "");
                editor.putString("shopimg", "");
                editor.putString("shopDescription", "");
                editor.putString("recommendName", "");
                editor.putString("isagent","");
                editor.apply();
                finishAllActivity();
                popupWindow.dismiss();
            }
        });

        View rootView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.activity_commodity_details, null);
        popupWindow.showAtLocation(rootView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * 选择规格里的价格
     */
    private TextView tvguigeprice;
    /**
     * 选择规格里的库存
     */
    private TextView tvguigekucun;
    private TextView tvguigeliyun;
    private ImageView ivguigeimage;
    private LinearLayout ll_guigekucun;

    /**
     * 展示规格的popupwindow
     */
    private void showguigePopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.popupwindow_choice_guige, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        ImageView ivimage = (ImageView) contentView.findViewById(R.id.iv_image);
        tvguigeprice = (TextView) contentView.findViewById(R.id.tv_price);
        tvguigeliyun = (TextView) contentView.findViewById(R.id.tv_liyun);
        tvguigekucun = (TextView) contentView.findViewById(R.id.tv_guige_kucun);
        ivguigeimage = (ImageView) contentView.findViewById(R.id.iv_image);
        ll_guigekucun = (LinearLayout) contentView.findViewById(R.id.ll_guigekucun);
        final TextView tvjian = (TextView) contentView.findViewById(R.id.tv_jian);
        final TextView tvjia = (TextView) contentView.findViewById(R.id.tv_jia);
        final TextView tvnum = (TextView) contentView.findViewById(R.id.tv_num);
        Button btntrue = (Button) contentView.findViewById(R.id.btn_true);
        ListView listviewgg = (ListView) contentView.findViewById(R.id.listview_guige);

        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (guigedata != null) {
            guigeadapter = new Guigeadapter(this, guigedata.getSpecs());
            listviewgg.setAdapter(guigeadapter);
            if (guigedata.getSpecs().size() > 0) {
                //创建装规格元素的数组
                strs = new int[guigedata.getSpecs().size()];
            }
            guigeadapter.setCallBack(this);

            if (ASUtils.isCanUse(goodsdata.getMarketprice())) {
                tvguigeprice.setText(NumberUtils.DecimalFormat(goodsdata.getMarketprice()));
            }
            if (ASUtils.isCanUse(goodsdata.getProfit())) {
                tvguigeliyun.setText(NumberUtils.DecimalFormat(goodsdata.getProfit()));
            }
            if (ASUtils.isCanUse(goodsdata.getThumb_url().get(0))) {
                Picasso.with(ChoicesDetailsActivity.this).load(goodsdata.getThumb_url().get(0)).placeholder(R.mipmap.zhanweitu2).into(ivguigeimage);
            }
            tvguigekucun.setText(goodsdata.getTotal());

            if (goodsdata.getThumb_url().size() > 0) {
                Picasso.with(this).load(goodsdata.getThumb_url().get(0)).placeholder(R.mipmap.zhanweitu2).into(ivimage);
            }
        }

        tvnum.setText(number + "");
        if (number == 1) {
            tvjian.setEnabled(false);
        }
        tvjian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (number > 1) {
                    number--;
                } else {
                    number = 1;
                }
                if (number == 1) {
                    tvjian.setEnabled(false);
                }
                tvnum.setText(number + "");
            }
        });

        tvjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(goodsdata.getShowtotal()) && Integer.parseInt(tvguigekucun.getText().toString().trim()) <= number) {
                    ToastUtils.makeToastShort("该规格商品库存不足");
                } else {
                    if (goodsdata.getUsermaxbuy() != 0 && number >= goodsdata.getUsermaxbuy() - goodsdata.getUserbuy()) {
                        ToastUtils.makeToastShort("已超过最大限购数量");
                    } else {
                        number++;
                        tvnum.setText(number + "");
                        tvjian.setEnabled(true);
                    }
                }
            }
        });
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number = 1;
                popWindow.dismiss();
            }
        });
        btntrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if ("1".equals(goodsdata.getShowtotal()) && "0".equals(tvguigekucun.getText().toString().trim())) {
                    ToastUtils.makeToastShort("商品库存为0，请选择别的规格");
                } else {
                    if (goodsdata.getUsermaxbuy() != 0 && number > goodsdata.getUsermaxbuy() - goodsdata.getUserbuy()) {
                        ToastUtils.makeToastShort("此账号已购买过" + goodsdata.getUsermaxbuy() + "件");
                    } else {
                        if (strs != null) {
                            for (int i = 0; i < strs.length; i++) {
                                if (strs[i] == 0) {
                                    isallcheck = false;
                                    break;
                                } else {
                                    isallcheck = true;
                                    continue;
                                }
                            }
                        } else {
                            isallcheck = true;
                        }

                        if (!isallcheck) {
                            ToastUtils.makeToastShort("请选择规格");
                        } else {
                            //判断是由哪个按钮调起的选择规格 ，做不同的事情
                            goodsnum = tvnum.getText().toString().trim();
                            if (type == 1) {
                                if (guige != null) {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum + "  " + guigetitle);
                                } else {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum);
                                }
                                if (ASUtils.isCanUse(guigelirun)) {
                                    tvlirun.setText(NumberUtils.DecimalFormat(guigelirun));
                                }
                                if (ASUtils.isCanUse(guigekuchun)) {
                                    tvkucun.setText(guigekuchun);
                                }
                                if (ASUtils.isCanUse(guigejiage)) {
                                    tvprice.setText(NumberUtils.DecimalFormat(guigejiage));
                                }
                            } else if (type == 2) {
                                if (ASUtils.isCanUse(guigelirun)) {
                                    tvlirun.setText(NumberUtils.DecimalFormat(guigelirun));
                                }
                                if (ASUtils.isCanUse(guigekuchun)) {
                                    tvkucun.setText(guigekuchun);
                                }
                                if (ASUtils.isCanUse(guigejiage)) {
                                    tvprice.setText(NumberUtils.DecimalFormat(guigejiage));
                                }
                                LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                                sucaiModel.addCart(goodID, goodsnum, guigeid, ChoicesDetailsActivity.this);
                                if (guige != null) {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum + "  " + guige);
                                } else {
                                    tvchoice.setText("已选:" + "数量×" + goodsnum);
                                }
                            } else if (type == 3) {
                                LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                                sucaiModel.buy(goodID, goodsnum, guigeid, ChoicesDetailsActivity.this);
                            }
                            //值还原
                            number = 1;
                            type = 1;
                            popWindow.dismiss();
                        }
                    }

                }

            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    /**
     * 判断是不是全部选择了规格
     */
    private boolean isallcheck;
    private StringBuffer allguige = new StringBuffer();
    private String guigejiage;
    private String guigekuchun;
    private String guigelirun;
    private String guigeid = null;
    private String guigeimage;
    private String guigetitle;

    /**
     * @param str 点击规格的回调
     */
    @Override
    public void gettext(int str, int position) {
        strs[position] = str;

        LogUtils.e("position:",position+"");

        if (strs != null) {
            for (int i = 0; i < strs.length; i++) {
                if (strs[i] == 0) {
                    isallcheck = false;
                    break;
                } else {
                    isallcheck = true;
                    continue;
                }
            }
        } else {
            isallcheck = true;
        }
        allguige.setLength(0);
        if (isallcheck) {
            int num = strs.length;
            int[] guigePx = new int[num];
            for (int i = 0; i < num; i++) {
                guigePx[i] = strs[i];
            }

            Arrays.sort(guigePx);
            for (int i = 0; i < guigedata.getSpecs().size(); i++) {
                allguige.append(guigePx[i]);
                LogUtils.e("allguige1:",allguige.toString());
                if (i != guigedata.getSpecs().size() - 1) {
                    allguige.append("_");
                }
            }

            guige = allguige.toString();
            for (int i = 0; i < guigedata.getOptions().size(); i++) {
                // LogUtils.e("guige2:",guigedata.getOptions().get(i).getSpecs());
                if (guige.equals(guigedata.getOptions().get(i).getSpecs())) {
                    guigejiage = guigedata.getOptions().get(i).getMarketprice();
                    guigekuchun = guigedata.getOptions().get(i).getStock();
                    guigelirun = guigedata.getOptions().get(i).getProfit();

                    guigeid = guigedata.getOptions().get(i).getId();
                    guigeimage = guigedata.getOptions().get(i).getThumb();
                    guigetitle = guigedata.getOptions().get(i).getTitle();
                }
            }
            if (ASUtils.isCanUse(guigejiage)) {
                tvguigeprice.setText(NumberUtils.DecimalFormat(guigejiage));
            }
            if (ASUtils.isCanUse(guigelirun)) {
                tvguigeliyun.setText(NumberUtils.DecimalFormat(guigelirun));
            }
            if (ASUtils.isCanUse(guigeimage)) {
                Picasso.with(this).load(guigeimage).placeholder(R.mipmap.zhanweitu2).into(ivguigeimage);
            } else {
                ivguigeimage.setImageResource(R.mipmap.zhanweitu2);
            }
            if (Integer.parseInt(guigekuchun) < 0) {
                tvguigekucun.setText("0");
            } else {
                tvguigekucun.setText(guigekuchun);
            }


        }

    }

    /**
     * 展示商品详情的数据
     */
    private void showgoodsData() {
        if ("1".equals(MyApp.loginMessage.getString("isagent",""))){
            mLlCommdityProfit.setVisibility(View.VISIBLE);
        }else {
            mLlCommdityProfit.setVisibility(View.INVISIBLE);
        }
        if ("0".equals(goodsdata.getShowtotal())) {
            llkucun.setVisibility(View.GONE);
        } else {
            tvkucun.setText(goodsdata.getTotal());
        }
        //展示图片
        imageResIDs = goodsdata.getThumb_url();
        //   LogUtils.e("URL",goodsdata.getThumb_url().toString());
        tvall.setText(imageResIDs.size() + "");
        prepareData();

        ViewPagerAdapter adapter = new ViewPagerAdapter(titleimage);
        viewpager.setAdapter(adapter);


        if ("1".equals( MyApp.loginMessage.getString("isagent", ""))) {
            ivshare.setVisibility(View.VISIBLE);
        }else {
            ivshare.setVisibility(View.INVISIBLE);
        }
        //展示内容
        tvtitle.setText(goodsdata.getTitle());
        mTvChoiceName.setText(mCateBean.getName());
        if (ASUtils.isCanUse(goodsdata.getProfit())) {
            tvlirun.setText(NumberUtils.DecimalFormat(goodsdata.getProfit()));
        }

        if (goodsdata.getBegin_price().equals(goodsdata.getEnd_price())) {
            llendprice.setVisibility(View.GONE);
            if (ASUtils.isCanUse(goodsdata.getMarketprice())) {
                tvprice.setText(NumberUtils.DecimalFormat(goodsdata.getMarketprice()));
            }
        } else {
            llendprice.setVisibility(View.VISIBLE);
            if (ASUtils.isCanUse(goodsdata.getBegin_price())) {
                tvprice.setText(NumberUtils.DecimalFormat(goodsdata.getBegin_price()));
            }
            if (ASUtils.isCanUse(goodsdata.getEnd_price())) {
                tvendprice.setText(NumberUtils.DecimalFormat(goodsdata.getEnd_price()));
            }
        }

        tvpeoplenum.setText(goodsdata.getGoodsOnsale());
        int num = goodsdata.getCartCount();
        showShopNum(num);

        //展示限购
        if (goodsdata.getUsermaxbuy() == 0) {
            llxiangou.setVisibility(View.GONE);
        } else {
            llxiangou.setVisibility(View.VISIBLE);
            tvxiangou.setText(goodsdata.getUsermaxbuy() + "");
        }

        if ("1".equals(goodsdata.getIstime())) {
            lltemai.setVisibility(View.VISIBLE);
            showTemaiDate();
            if (timer == null) {
                timer = new Timer();
            } else {
                timer.cancel();
                timer = new Timer();
            }
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg = handler.obtainMessage();
                    handler.sendMessage(msg);
                }
            }, 0, 999);
        } else {
            lltemai.setVisibility(View.GONE);
        }
    }

    /**
     * 展示购物车数量
     *
     * @param num
     */
    private void showShopNum(int num) {
        badgeView.setTargetView(llCart);
        badgeView.setBadgeMargin(30, 0, 0, 30);
        badgeView.setBadgeCount(num);
    }


    /**
     * 展示特卖时间
     */
    private void showTemaiDate() {
        if (System.currentTimeMillis() / 1000 < Long.parseLong(goodsdata.getTimestart())) {
            iscanbuy = false;
            tvstuta.setText("距离本场开始");
            Long time = Long.parseLong(goodsdata.getTimestart()) - System.currentTimeMillis() / 1000;
            String[] strs = DateUtil.getDaoJiShiTimeUnixs(time).split(":");
            tvhour.setText(NumberUtils.oneTtwo(strs[0]));
            tvminute.setText(NumberUtils.oneTtwo(strs[1]));
            tvsecond.setText(NumberUtils.oneTtwo(strs[2]));
            tvmaohao.setVisibility(View.VISIBLE);
            tvmaohao2.setVisibility(View.VISIBLE);
        } else if (System.currentTimeMillis() / 1000 > Long.parseLong(goodsdata.getTimestart()) && System.currentTimeMillis() / 1000 < Long.parseLong(goodsdata.getTimeend())) {
            iscanbuy = true;
            tvstuta.setText("距离本场结束");
            Long time = Long.parseLong(goodsdata.getTimeend()) - System.currentTimeMillis() / 1000;
            String[] strs = DateUtil.getDaoJiShiTimeUnixs(time).split(":");
            tvhour.setText(NumberUtils.oneTtwo(strs[0]));
            tvminute.setText(NumberUtils.oneTtwo(strs[1]));
            tvsecond.setText(NumberUtils.oneTtwo(strs[2]));
            tvmaohao.setVisibility(View.VISIBLE);
            tvmaohao2.setVisibility(View.VISIBLE);
        } else {
            iscanbuy = false;
            tvstuta.setText("活动已过期");
            tvhour.setVisibility(View.GONE);
            tvminute.setVisibility(View.GONE);
            tvsecond.setVisibility(View.GONE);
            tvmaohao.setVisibility(View.GONE);
            tvmaohao2.setVisibility(View.GONE);

        }
    }

    /**
     * @param object 获取商品详情成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        mGoodsDetailsData = (ChoiceDetailsData) object;

        goodsdata = mGoodsDetailsData.getGoods();

        mCateBean = mGoodsDetailsData.getCate();
        showgoodsData();
        sucaiModel.getSucaiData(goodID, this);
    }

    /**
     * @param object 获取商品详情失败
     */
    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();

    }

    /**
     * 展示素材页面数据
     */
    private void showSucaiData() {
        if (adapter == null) {
            adapter = new SucaiAdapter(this, sucaidata);
            lvsucai.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setCallBack(this);
        LoadingDialogUtils.dismiss();
    }

    private List<GoodsSucai_Data> goodsSucai_datas;

    /**
     * @param object 获取商品素材成功
     */
    @Override
    public void ongetSucaiSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        goodsSucai_datas = (List<GoodsSucai_Data>) object;
//        if (sucaipage == 1) {
//            sucaidata.clear();
//        } else {
//            if (goodsSucai_datas.size() == 0) {
////                ToastUtils.makeToastShort("没有更多了");
//                return;
//            }
//        }
        sucaidata.clear();
        sucaidata.addAll(goodsSucai_datas);
        if (sucaidata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        showSucaiData();

    }


    /**
     * @param object 获取商品素材失败
     */
    @Override
    public void ongetSucaiError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 加入购物车成功
     */
    @Override
    public void onaddCartSuccess(Object object) {
        ToastUtils.makeToastShort("加入购物车成功");
        JSONObject jsonObject = (JSONObject) object;
        int num = jsonObject.optInt("cartSum");
        showShopNum(num);
    }

    /**
     * @param object 加入购物车失败
     */
    @Override
    public void onaddCartError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 买成功的回调
     */
    @Override
    public void onbuySuccess(Object object) {
        Buy_Data data = (Buy_Data) object;
        Intent intent = new Intent(this, OrderAffirmActivity.class);
        intent.putExtra("goods_data", data);
        intent.putExtra("optionid", guigeid);
        intent.putExtra("goodsid", goodID);
        intent.putExtra("total", goodsnum);
        startActivity(intent);
    }

    /**
     * @param object 买失败的回调
     */
    @Override
    public void onbuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        Intent intent = new Intent(this, AddAddressActivity.class);
        startActivity(intent);
    }


    @Override
    public void onRefresh() {
//        sucaipage = 1;
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        sucaiModel.getSucaiData(goodID, this);
    }

    public String getGoodID() {
        return goodID;
    }


    /**
     * @param object 获取分享链接成功
     */
    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, goodsdata.getTitle(), goodsdata.getMarketprice(), goodsdata.getIstime(), goodsdata.getTimestart(), goodsdata.getTimeend(), goodsdata.getThumb_url().get(0), wxURL);
        } else if (num == WEIXINHAOYOU) {
            if (type == 1) {
                ShareUtils.wxshare(goodsdata.getTitle(), goodsdata.getThumb_url().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
            } else if (type == 2) {
                ShareUtils.wxshare(goodsSucai_datas.get(position).getTitle(), goodsSucai_datas.get(position).getThumb_url().get(0), goodsSucai_datas.get(position).getDetail(), wxURL);
            }
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(goodsdata.getTitle(), goodsdata.getThumb_url().get(0), wxURL);
        }

    }

    /**
     * @param object 获取分享链接失败
     */
    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }


    /**
     * @param data
     * @param position 素材页面的分享的回调
     */
    @Override
    public void sucarShare(GoodsSucai_Data data, int position) {
      /*  showShareGoodsPopupwindow(data, position);
        this.position = position;*/
        showSharePopupwindow();
    }

    /**
     * 横向的素材recycleview是不是在滑动
     */
    private boolean iscroll;
    private int position;


    private int tpye = 0;

    /**
     * 展示分享的popupwindow
     */
    private void showSharePopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(ChoicesDetailsActivity.this).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (goodsdata != null) {
            tvprice.setText(NumberUtils.DecimalFormat(goodsdata.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(goodsdata.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(goodsdata.getId(), null, LIANJIE, ChoicesDetailsActivity.this);
                    } else {
                        ShareUtils.copyLianjie(ChoicesDetailsActivity.this, wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(goodsdata.getId(), null, ERWEIMA, ChoicesDetailsActivity.this);
                    } else {
                        ShareUtils.ereima3(ChoicesDetailsActivity.this, goodsdata.getTitle(), goodsdata.getMarketprice(), goodsdata.getIstime(), goodsdata.getTimestart(), goodsdata.getTimeend(), goodsdata.getThumb_url().get(0), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        type = 1;
                        LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(goodsdata.getId(), null, WEIXINHAOYOU, ChoicesDetailsActivity.this);
                    } else {
                        ShareUtils.wxshare(goodsdata.getTitle(), goodsdata.getThumb_url().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(ChoicesDetailsActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(goodsdata.getId(), null, PENGYOUQUAN, ChoicesDetailsActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(goodsdata.getTitle(), goodsdata.getThumb_url().get(0), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 获取商品规格成功
     *
     * @param object
     */
    @Override
    public void getGuigeSuccess(Object object) {
        guigedata = (Guige_Data) object;
        showGuige();

    }

    private void showGuige() {
        if (type == 1) {//点击了选择规格
            showguigePopupwindow();
        } else if (type == 2) {//点击加入购物车
            num = goodsdata.getTotal();
            if (ASUtils.isCanUse(num) && Integer.parseInt(num) > 0) {
                showguigePopupwindow();
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }
        } else if (type == 3) {//点击购买
            //库存量
            num = goodsdata.getTotal();
            if (ASUtils.isCanUse(num) && Integer.parseInt(num) > 0) {
                if (guigedata.getSpecs() != null) {
                    if (guige != null && goodsnum != null) {
                        for (int i = 0; i < guigedata.getOptions().size(); i++) {
                            if (guige.equals(guigedata.getOptions().get(i).getSpecs())) {
                                guigeid = guigedata.getOptions().get(i).getId();
                            }
                        }
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        sucaiModel.buy(goodID, goodsnum, guigeid, this);
                    } else {
                        showguigePopupwindow();
                    }
                } else {
                    if (goodsnum == null) {
                        showguigePopupwindow();
                    } else {
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        sucaiModel.buy(goodID, goodsnum, guigeid, this);
                    }
                }
            } else {
                ToastUtils.makeToastShort("商品库存为0");
            }

        }
    }

    /**
     * 获取商品规格失败
     *
     * @param object
     */
    @Override
    public void getGuigeError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 点击标题复制
     */
    private void fuzhiPopupwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_fuzhi_biaoti, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popWindow.setContentView(contentView);
        //设置各个控件的点击响应
        RelativeLayout rlfuzhi = (RelativeLayout) contentView.findViewById(rl_fuzhi);
        rlfuzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.copyLianjie(ChoicesDetailsActivity.this, tvtitle.getText().toString().trim());
                popWindow.dismiss();
            }
        });
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.showAsDropDown(tvtitle, 0, -tvtitle.getHeight() - AndroidUtil.dip2px(this, 40));
//        popWindow.showAtLocation(tvtitle, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f, ChoicesDetailsActivity.this);
            }
        });
        setAlpha(1.0f, ChoicesDetailsActivity.this);
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x1111:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                }
                break;
        }
    }

    private void init() {

        if (!NetUtils.hasDataConnection(ChoicesDetailsActivity.this)) {
            Toast.makeText(ChoicesDetailsActivity.this, "当前没有网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        LoadingDialogUtils.showProgress(this);
        if (MyApp.isKFSDK) {
            LoadingDialogUtils.dismiss();
            getPeers();
        } else {
            startKFService();
        }
    }

    private void getPeers() {
        IMChatManager.getInstance().getPeers(new GetPeersListener() {
            @Override
            public void onSuccess(List<Peer> peers) {
                System.out.println("获取技能组成功");
                if (peers.size() > 1) {
                    PeerDialog dialog = new PeerDialog();
                    Bundle b = new Bundle();
                    b.putSerializable("Peers", (Serializable) peers);
                    b.putString("type", "init");
                    dialog.setArguments(b);
                    dialog.show(getFragmentManager(), "");

                } else if (peers.size() == 1) {
                    startChatActivity(peers.get(0).getId());
                } else {
                    startChatActivity("");
                }
            }

            @Override
            public void onFailed() {
                System.out.println("获取技能组失败了");
            }
        });
    }

    private void startKFService() {
        new Thread() {
            @Override
            public void run() {
                IMChatManager.getInstance().setOnInitListener(new InitListener() {
                    @Override
                    public void oninitSuccess() {
                        MyApp.isKFSDK = true;
                        LoadingDialogUtils.dismiss();
                        getPeers();
                        Log.d("MobileApplication", "sdk初始化成功");
                    }
                    @Override
                    public void onInitFailed() {
                        MyApp.isKFSDK = false;
                        LoadingDialogUtils.dismiss();
                        Toast.makeText(ChoicesDetailsActivity.this, "客服初始化失败", Toast.LENGTH_SHORT).show();
                        Log.d("MobileApplication", "sdk初始化失败, 请填写正确的accessid");
                    }
                });
                //初始化IMSdk,填入相关参数
                IMChatManager.getInstance().init(MyApp.getInstance(), "action", accessID, MyApp.loginMessage.getString("mobile", ""), MyApp.loginMessage.getString("mobile", ""));

            }
        }.start();

    }

    private void startChatActivity(String peerId) {
        Intent chatIntent = new Intent(ChoicesDetailsActivity.this, ChatActivity.class);
        chatIntent.putExtra("PeerId", peerId);
        startActivity(chatIntent);
    }
}
